package com.usabb.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.ifast.common.component.oss.support.UploadServer;
import com.usabb.api.dto.GuestCaseDTO;
import com.usabb.enums.BizTypeEnum;
import com.usabb.utils.UploadFileNameUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.usabb.dao.GuestCaseDao;
import com.usabb.domain.GuestCaseDO;
import com.usabb.service.GuestCaseService;
import com.ifast.common.base.CoreServiceImpl;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 
 * <pre>
 * 客人感言
 * </pre>
 * <small> 2019-08-19 18:03:26 | Aron</small>
 */

@Slf4j
@Service
@AllArgsConstructor
public class GuestCaseServiceImpl extends CoreServiceImpl<GuestCaseDao, GuestCaseDO> implements GuestCaseService {
    private static final String PRIFFIX = "GuestCaseAvatar";
    private UploadServer uploader;

    @Override
    public List<GuestCaseDO> getByBizTypeAndBizId(BizTypeEnum bizTypeEnum, final Long bizId) {
        GuestCaseDO guestCaseParam = new GuestCaseDO();
        guestCaseParam.setBizId(bizId);
        guestCaseParam.setBizType(bizTypeEnum.name());
        Wrapper<GuestCaseDO> wrapper = new EntityWrapper<>(guestCaseParam);

        return this.selectList(wrapper);
    }

    @Override
    public List<GuestCaseDTO> getBy(BizTypeEnum bizTypeEnum, final Long bizId) {
        List<GuestCaseDO> guestCaseDOS = getByBizTypeAndBizId(bizTypeEnum, bizId);

        return guestCaseDOS.stream().map(it -> GuestCaseDTO.of(it)).collect(Collectors.toList());
    }

    /**
     * upload + save
     */
    @Override
    public void addWithImage(GuestCaseDO guestCase, MultipartFile avatarFile) {
        final String url = upload(avatarFile);
        guestCase.setAvatar(url);

        this.insert(guestCase);
    }

    @Override
    public void updateWithImage(GuestCaseDO guestCase, MultipartFile avatarFile) {
        final String url = upload(avatarFile);
        guestCase.setAvatar(url);

        this.updateById(guestCase);
    }

    public String upload(MultipartFile multipartFile) {
        log.info("input: multipartFile:{}", multipartFile.getOriginalFilename());
        final String fileNameOnClient = multipartFile.getOriginalFilename();
        final String fileName = UploadFileNameUtils.getFileName(fileNameOnClient, PRIFFIX);

        String url = null;
        try {
            url = uploader.upload(multipartFile.getBytes(), fileName);
        } catch (IOException e) {
            log.error("File upload IO Exception. file:{}",  fileNameOnClient, e);
            return StringUtils.EMPTY;
        }

        return url;
    }

}
